package com.jrtc.api.controller.base;

import com.aliyuncs.utils.StringUtils;
import com.auth0.jwt.JWT;
import com.jrtc.base.config.LoginException;
import com.jrtc.base.config.ParamException;
import com.jrtc.base.util.IpUtil;
import com.jrtc.base.util.RedisUtil;
import com.jrtc.base.util.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Component
public class BaseController {
    @Autowired
    private RedisUtil redis;

    /**
     * 获取当前登录的用户
     */
    /*public UserBO getLoginUser(HttpServletRequest request){
        String token = request.getHeader("token");
        if (org.apache.commons.lang.StringUtils.isBlank(token)){
           return null;
        }
        try{
            String mobile =  JWT.decode(token).getAudience().get(0);
            UserBO userByPhone = userService.getUserByPhone(mobile);
            if (userByPhone!=null){
                return userByPhone;
            }else{
                throw new LoginException("登录已过期，请重新登录");
            }
        }catch (Exception e){
            throw new LoginException("登录已过期，请重新登录");
        }
    }*/

    //验证参数
    public void verification(Object... obj) throws ParamException {
        if (obj == null || obj.length < 1) {
            throw new ParamException("参数异常");
        }
        for (Object o : obj) {
            if (o instanceof String) {
                if (StringUtils.isEmpty((String) o)) {
                    throw new ParamException("参数异常");
                }
            } else {
                if (o == null) {
                    throw new ParamException("参数异常");
                }
            }
        }
    }

    /**
     * 用户登录
     * @Param mobile 账号
     * @Param password 密码
     */
    public String loginUser(String mobile, String password, HttpServletRequest request) {
        //使用账户和密码生成token
        TokenUtil tokenUtil = new TokenUtil();
        String token = tokenUtil.getToken(mobile, password);

        //拿到token以后，存入redis，并保存ip，有效期一周
        Map<String, String> redisMap = new HashMap<>();
        redisMap.put("token", token);

        IpUtil ipUtil = new IpUtil();
        redisMap.put("ip", ipUtil.getIpAddr(request));

        //账号为key token和ip为value 保存一周
        redis.set("user" + mobile, redisMap, 60 * 60 * 24 * 7);
        return token;
    }


}
